//
//  UIImage+Extensions.swift
//  EasePods
//
//  Created by 易先生 on 2024/5/23.
//

import Foundation

extension UIImage {
    
    /// 图片缩放
    /// - Parameters:
    ///   - targetSize: 缩放大小
    /// - Returns: 图片
    func scaleImage(targetSize: CGSize) -> UIImage {
        let size = self.size
        
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        
        // 根据宽高比例决定缩放比例
        let newSize: CGSize
        if widthRatio > heightRatio {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        }
        
        // 创建一个绘制区域
        let rect = CGRect(origin: .zero, size: newSize)
        
        // 开始绘制
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage ?? UIImage() // 如果失败返回一个空白图片
    }
}
